#include "stm32f10x.h"                  // Device header
#include "Delay.h"

void HC_SR04_Init(void)
{
	//启用GPIOA6
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	GPIO_ResetBits(GPIOA,GPIO_Pin_5);
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); //TIM3使能
	TIM_InternalClockConfig(TIM3); //选择内部时钟作为时钟源，可省略
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //滤波采样分频
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
	TIM_TimeBaseInitStructure.TIM_Period = 65536-1; //ARR自动重装器的值
	TIM_TimeBaseInitStructure.TIM_Prescaler = 144-1; //PSC预分频
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; //重复计数器，先不用管
	TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); //增长间隔为0.000002s
	
	
	//默认为低电平，上升沿表明时间开始，下降沿表明时间结束，使用IC的两个通道捕获
	TIM_ICInitTypeDef TIM_ICInitStructure;
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
	TIM_ICInitStructure.TIM_ICFilter = 0xf; //滤波器
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //下降沿触发
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //不分频
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //将TIM3_CH1->TI1->TI1FP1 映射到 IC1
	TIM_PWMIConfig(TIM3,&TIM_ICInitStructure);//通道2为上升沿触发
	TIM_SelectInputTrigger(TIM3,TIM_TS_TI2FP2); //TIM_TS_TI2FP2的上升沿触发从模式，将CNT清零
	TIM_SelectSlaveMode(TIM3,TIM_SlaveMode_Reset);
	TIM_Cmd(TIM3,ENABLE); //启动计时器
}

float HC_SR04_Measure()
{
		GPIO_SetBits(GPIOA,GPIO_Pin_5);
		Delay_us(12);
		GPIO_ResetBits(GPIOA,GPIO_Pin_5);
		TIM_SetCounter(TIM3,0);
		Delay_ms(200);
		return (TIM_GetCapture2(TIM3)-TIM_GetCapture1(TIM3))*0.000002*34000/2;
}
